﻿using CommonLibrary.Str;
using Common;
using Microsoft.Win32;
using Panuon.UI.Silver;
using Service.DtoModel.DeskApp;
using Service.Implements;
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace RunApp.PartialViews.Business
{
    /// <summary>
    /// AddProWin.xaml 的交互逻辑
    /// </summary>
    public partial class AddProWin : WindowX
    {
        #region Property       
        RoomService roomservice = new RoomService();
        MenuService menuService = new MenuService();
        SysTypeService TypeService = new SysTypeService();
        #endregion

        public AddProWin()
        {
            InitializeComponent();
            ShowCurImg.Visibility = Visibility.Collapsed;
            BigimgBlock.Visibility = Visibility.Collapsed;
            GetTabTypeList();
        }

        #region Event
        /// <summary>
        /// 关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
        /// <summary>
        /// 最小化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnMin_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }
        /// <summary>
        /// 最大化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnMax_Click(object sender, RoutedEventArgs e)
        {
            if (WindowState == WindowState.Maximized) WindowState = WindowState.Normal;
            else WindowState = WindowState.Minimized;
        }
        /// <summary>
        /// 筛选菜品类别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CmbCustom_SearchTextChanged(object sender, Panuon.UI.Silver.Core.SearchTextChangedEventArgs e)
        {
            if (!IsLoaded) return;
            foreach (ComboBoxItem item in cmbTabs.Items)
            {
                item.Visibility = item.Content.ToString().Contains(e.Text) ? Visibility.Visible : Visibility.Collapsed;
            }
        }
        /// <summary>
        /// 保存再新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            var _res = SaveAddDate();
            if (_res == (int)ApiEnum.Status)
            {
                txtProName.Text = string.Empty;
                txtCost.Text = string.Empty;
                txtPrice.Text = string.Empty;
                txtScalar.Text = string.Empty;
                txtUnit.Text = string.Empty;
                cmbTabs.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 保存并返回
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            var _res = SaveAddDate();
            if (_res == (int)ApiEnum.Status) Close();
        }
        /// <summary>
        /// 限制“菜品单价”文本框只允许输入数字（包含小数）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtPrice_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            Helpers.ValidationTextbox.ValidaDecimal(sender, e);
        }
        /// <summary>
        /// 限制“菜品库存量”文本框只允许输入数字（不包含小数）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TxtScalar_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            Helpers.ValidationTextbox.ValidaNumber(sender, e);
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnUpImg_Click(object sender, RoutedEventArgs e)
        {
            SelImage();
        }
        /// <summary>
        /// 预览图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ShowCurImg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            InfoBlock.Visibility = Visibility.Collapsed;
            BigimgBlock.Visibility = Visibility.Visible;
        }
        /// <summary>
        /// 退出预览图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnCloseBigimg_Click(object sender, RoutedEventArgs e)
        {
            InfoBlock.Visibility = Visibility.Visible;
            BigimgBlock.Visibility = Visibility.Collapsed;
        }
        #endregion

        #region Function
        private void GetTabTypeList()
        {
            var _res = TypeService.GetListAsync().Result;
            if (_res.statusCode == (int)ApiEnum.Status)
            {
                List<ComboBoxItem> tabTypeList = new List<ComboBoxItem>();
                var _tabTypes = _res.data;
                var defObj = new ComboBoxItem { Tag = "0", Content = "请选择菜品类型" };
                tabTypeList.Add(defObj);
                foreach (var item in _tabTypes)
                {
                    var curObj = new ComboBoxItem
                    {
                        Tag = item.typeId,
                        Content = item.typeName
                    };
                    tabTypeList.Add(curObj);
                }
                cmbTabs.SelectedIndex = 0;
                cmbTabs.ItemsSource = tabTypeList;
            }
        }
        private int SaveAddDate()
        {
            var _res = (int)ApiEnum.Error;
            try
            {
                #region 验证
                var _typeId = 0;
                var _selItem = cmbTabs.SelectedItem;
                if (_selItem is ComboBoxItem)
                {
                    var _cmbItemobj = (ComboBoxItem)_selItem;
                    var _tId = _cmbItemobj.Tag.ToString();
                    int.TryParse(_tId, out _typeId);
                }
                if (_typeId == 0)
                {
                    Notice.Show("请录入菜品类型！", "提示", 3, MessageBoxIcon.Warning);
                    return _res;
                }
                var _rname = txtProName.Text.Trim();
                if (string.IsNullOrEmpty(_rname))
                {
                    Notice.Show("请录入菜品名称！", "提示", 3, MessageBoxIcon.Warning);
                    return _res;
                }                
                double _proprice = -1; double.TryParse(txtPrice.Text.Trim(), out _proprice);
                if (_proprice < 0)
                {
                    Notice.Show("请录入菜品单价！", "提示", 3, MessageBoxIcon.Warning);
                    return _res;
                }
                var _proscalar = 0; int.TryParse(txtScalar.Text.Trim(), out _proscalar);
                if (_proscalar == 0)
                {
                    Notice.Show("请录入菜品库存量！", "提示", 3, MessageBoxIcon.Warning);
                    return _res;
                }
                var _prounit = txtUnit.Text.Trim();
                if (string.IsNullOrEmpty(_prounit))
                {
                    Notice.Show("请录入菜品单位！", "提示", 3, MessageBoxIcon.Warning);
                    return _res;
                }
                #endregion

                var _proImgName = _rname + string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now);
                var rootImagPath = Directory.GetCurrentDirectory().Replace(@"\bin\Debug", "") + @"\Resources\proImg\" + _proImgName + ".png";
                double _procost = 0; double.TryParse(txtCost.Text.Trim(), out _procost);
                var addObj = new Service.DtoModel.DeskApp.Menu
                {
                    mtId = _typeId,
                    msName = _rname,
                    msSpell = Str.PinYin(_rname),
                    msUnit = _prounit,
                    msPrice = _proprice,
                    msScalar = _proscalar,
                    msCost = _procost,
                    proImg = rootImagPath,//"/RunApp;component/Resources/proImg/" + _proImgName + ".png",
                    msMoney = 0,//当前业务还未涉及实际库存存放，暂定为0
                    stId = 0,//当前业务还未涉及实际库存存放，暂定为0
                    createDate = DateTime.Now
                };
                var _addRes = menuService.AddAsync(addObj).Result;
                if (_addRes.statusCode == (int)ApiEnum.Status)
                {
                    bool _isSave = false;
                    try
                    {
                        SaveImage(rootImagPath);
                        _isSave = true;
                    }
                    catch (Exception ex)
                    {
                        Logger.Default.Error("保存产品图片到本地时，出现异常。", ex);
                    }
                    if (_isSave)
                    {
                        Notice.Show("添加成功！", "提示", 3, MessageBoxIcon.Success);
                        _res = (int)ApiEnum.Status;
                    }
                    else
                    {
                        Notice.Show("添加失败！", "提示", 3, MessageBoxIcon.Error);
                        _res = (int)ApiEnum.Error;
                    }
                }
                else
                {
                    Notice.Show("添加失败！", "提示", 3, MessageBoxIcon.Error);
                    Logger.Default.ProcessError(_addRes.statusCode, "添加菜品失败");
                }
                _res = _addRes.statusCode;
            }
            catch (Exception ex)
            {
                Logger.Default.Error("添加菜品出现异常", ex);
            }
            return _res;
        }
        private void SelImage()
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = "图片文件(.jpg;.bmp;.png;.jpeg)|*.jpg;*.png;*.jpeg;";
                ofd.InitialDirectory = @"C:\Users\Administrator\Desktop";//文件选择的默认路径 
                if (ofd.ShowDialog() == true)
                {
                    string filePath = ofd.FileName;
                    char[] separator = { '\\' };
                    string[] partPath = filePath.Split(separator);
                    ShowCurImg.Source = new BitmapImage(new Uri(filePath));
                    BigImg.Source = new BitmapImage(new Uri(filePath));
                    ShowCurImg.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                Logger.Default.Error("上传图片异常", ex);
            }
        }
        private void SaveImage(string path)
        {
            if (!string.IsNullOrEmpty(path))
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create((BitmapSource)this.ShowCurImg.Source));
                FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);//Directory.GetCurrentDirectory()
                encoder.Save(fileStream);
                fileStream.Close();
            }
        }
        private void DelImage(string path)
        {
            if (!FileHelper.FileIsUsed(path)) FileHelper.DeleteDirectory(path);
        }
        #endregion        
    }
}
